package com.miaosha.redis.hash;

import redis.clients.jedis.Jedis;

/**
 * @author lsq
 * @create 2021-10-09 7:31
 * @description
 * @menu
 **/
public class ShortUrl {

    private final static String HTTP_PRE = "http://t.cn/";
    private static final String X36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String[] X36_ARRAY = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".
            split(",");
    public static final String SHORT_URL_ACCESS_COUNT = "short_url_access_count";
    public static final String SHORT_URL_SEED = "short_url_seed";
    public static final String SHORT_URL_MAPPING = "short_url_mapping";
    private Jedis jedis = new Jedis("182.42.113.98", 6379);


    public ShortUrl() {
        jedis.set(SHORT_URL_SEED, "5145145825");
    }

    public String getShortUrl(String url) {


        long num = jedis.incr(SHORT_URL_SEED);

        String shortUrl = tenTo36(num);
        jedis.hset(SHORT_URL_ACCESS_COUNT, shortUrl, "0");
        jedis.hset(SHORT_URL_MAPPING, shortUrl, url);
        return shortUrl;
    }

    /**
     * 十进制转成三十六进制
     *
     * @param num 种子数
     * @return
     */
    public static String tenTo36(long num) {

        StringBuffer sBuffer = new StringBuffer();

        if (num == 0) {
            sBuffer.append("0");
        }
        while (num > 0) {
            sBuffer.append(X36_ARRAY[(int) num % 36]);
            num = num / 36;
        }

        return sBuffer.reverse().toString();
    }

    /**
     * 给短连接地址访问次数增加
     *
     * @param shortUrl
     */
    public void incrementShortUrlAccessCount(String shortUrl) {
        jedis.hincrBy(SHORT_URL_ACCESS_COUNT, shortUrl, 1);
    }

    /**
     * 获取短连接地址的访问次数
     *
     * @param shortUrl
     * @return
     */
    public long getShortUrlAccessCount(String shortUrl) {
        return Long.valueOf(jedis.hget(SHORT_URL_ACCESS_COUNT, shortUrl));
    }

    public static void main(String[] args) {

        ShortUrl shortUrlObj = new ShortUrl();
        String shortUrl = shortUrlObj.getShortUrl("http://redis.com/index.html");
        System.out.println("页面上访问的短链接地址：" + HTTP_PRE + shortUrl);

        for (int i = 0; i < 152; i++) {
            shortUrlObj.incrementShortUrlAccessCount(shortUrl);
        }

        long shortUrlAccessCount = shortUrlObj.getShortUrlAccessCount(shortUrl);
        System.out.println("短链接访问的次数：" + shortUrlAccessCount);
    }
}
